from django.contrib.auth.hashers import make_password

from apps.cbsp.models import Cbsp_Bi_Records
from apps.pbi.models import BusinessOpportunity, Contract
from apps.system.models import Company, Region, ToDoList, WorkflowStep, Workflow, OperationRecord
from extensions.common.base import *
from extensions.serializers import *
from extensions.exceptions import *
from apps.system.models import *
# from apps.goods.models import *
from apps.pbi.models import *




class CompaniesSerializer(BaseSerializer):

    class Meta:
        model = Company
        read_only_fields = ['id','type']
        fields = ['name','index','coding_abbreviation',*read_only_fields]

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class ClientsSerializer(BaseSerializer):

    class Meta:
        model = Client
        fields = ['id','name']

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class BusinessOpportunitySerializer(BaseSerializer):
    client_name = CharField(source='client.name', read_only=True, label='甲方单位')

    class Meta:
        model = BusinessOpportunity
        fields = ['id', 'name', 'number', 'client_name', 'is_frame', 'budget']


class Cbsp_Bi_RecordsSerializer(BaseSerializer):
    class Meta:
        model = Cbsp_Bi_Records
        fields = ['id', 'name', 'employee_number', 'sfz_number']


class BusinessOpportunity_orderSerializer(BaseSerializer):

    class ContractSerializer(BaseSerializer):
        class Meta:
            model = Contract
            fields = ['id', 'name', 'number']

    contract = ContractSerializer(source='Contract_business_opportunity',many=True, read_only=True, label='签约合同')

    class Meta:
        model = BusinessOpportunity
        fields = ['id','name','number','is_frame','contract']

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        if 'contract' in rep and rep['contract']:
            contract_data = rep.pop('contract')[0]
            # rename contract fields
            contract_data = {f'contract_{k}': v for k, v in contract_data.items()}
            rep.update(contract_data)
        return rep



class TodolistsSerializer(BaseSerializer):

    class Meta:
        model = ToDoList
        read_only_fields = ['id']
        fields = ['name','deadline','stage','status','finish_time','create_time','creator','del_flag','remark',*read_only_fields]


class OperationRecordSerializer(BaseSerializer):
    company_name = CharField(source='user.company.name', read_only=True, label='公司')
    name = CharField(source='user.name', read_only=True, label='姓名')
    class Meta:
        model = OperationRecord
        fields = "__all__"


class LoginLogSerializer(BaseSerializer):
    company_name = CharField(source='user.company.name', read_only=True, label='公司')
    name = CharField(source='user.name', read_only=True, label='公司')
    class Meta:
        model = LoginLog
        fields = "__all__"




class DepartmentsSerializer(BaseSerializer):

    class Meta:
        model = Department
        read_only_fields = ['id','type']
        fields = ['name','index',*read_only_fields]

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class JobsSerializer(BaseSerializer):

    class Meta:
        model = Job
        read_only_fields = ['id',]
        fields = ['name','index',*read_only_fields]

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class DictsSerializer(BaseSerializer):

    class Dict_itemsSerializer(BaseSerializer):

        class Meta:
            model = Dict_item
            fields = ['id', 'name','description']

    # sex_display = CharField(source='get_sex_display', read_only=True, label='性别')
    dict_items = Dict_itemsSerializer(source='dict_item', many=True, read_only=True, label='字典项')

    class Meta:
        model = Dict
        read_only_fields = ['id','dict_items']
        fields = ['name','code','description',*read_only_fields]
        extra_kwargs = {'dict_item': {'required': False}}

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class RegionsSerializer(BaseSerializer):

    class Meta:
        model = Region
        read_only_fields = ['id']
        fields = ['region_name','region_parent_id','region_short_name','index','region_level',*read_only_fields]



class PermissionGroupSerializer(BaseSerializer):

    class PermissionItemSerializer(BaseSerializer):

        class Meta:
            model = Permission
            fields = ['id', 'name', 'code']

    permission_items = PermissionItemSerializer(source='permissions', many=True, label='权限')

    class Meta:
        model = PermissionGroup
        fields = ['id', 'name', 'permission_items']




class RoleSerializer(BaseSerializer):

    class Meta:
        model = Role
        read_only_fields = ['id']
        fields = ['name', 'remark', 'permissions', *read_only_fields]

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class UserSerializer(BaseSerializer):

    class RoleItemSerializer(BaseSerializer):

        class Meta:
            model = Role
            fields = ['id', 'name']

    # sex_display = CharField(source='get_sex_display', read_only=True, label='性别')
    role_items = RoleItemSerializer(source='roles', many=True, read_only=True, label='角色Item')

    class CompanyItemSerializer(BaseSerializer):

        class Meta:
            model = Company
            fields = ['id', 'name','coding_abbreviation','index']

    # sex_display = CharField(source='get_sex_display', read_only=True, label='性别')
    company_item = CompanyItemSerializer(source='company', many=False, read_only=True, label='公司Item')

    class DepartmentItemSerializer(BaseSerializer):

        class Meta:
            model = Department
            fields = ['id', 'name','index']

    # sex_display = CharField(source='get_sex_display', read_only=True, label='性别')
    department_item = DepartmentItemSerializer(source='department', many=False, read_only=True, label='部门Item')

    class Meta:
        model = User
        read_only_fields = ['id', 'company_item','department_item', 'is_manager', 'role_items', 'permissions', 'create_time']
        fields = ['username', 'name', 'phone', 'email', 'roles', 'company', 'department', 'job', 'is_active',
                  *read_only_fields]

    def validate_username(self, value):
        self.validate_unique({'username': value}, message=f'用户名[{value}]已存在')
        return value

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value

    def validate_roles(self, instances):
        instances = self.validate_foreign_key_set(Role, instances, message='角色不存在')
        return instances

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data['username'])
        return super().create(validated_data)

    def save(self, **kwargs):
        permissions = []
        if roles := self.validated_data.get('roles'):
            permissions = {permission.code for role in roles.prefetch_related('permissions').all()
                           for permission in role.permissions.all()}

        kwargs['permissions'] = list(permissions)
        return super().save(**kwargs)



class WorkflowSerializer(BaseSerializer):
    class WorkflowStepSerializer(BaseSerializer):
        approval_permission_code = CharField(source='approval_permission.code', read_only=True, label='审批权限')
        class Meta:
            model = WorkflowStep
            fields = ['id', 'name', 'approval_permission_code', 'step_number', 'is_final_step']

    steps = WorkflowStepSerializer(many=True, read_only=True)

    class Meta:
        model = Workflow
        fields = ['id', 'name', 'steps']


__all__ = [
    'PermissionGroupSerializer',
    'RoleSerializer', 'UserSerializer',
    'DepartmentsSerializer', 'JobsSerializer',
    'DictsSerializer',
    'WorkflowSerializer',
]
